/* api */
import { getConnectorInsertSelectCall } from '@src/modules/connector/api'
/* model */
import { ConnectorModuleComponentNameEnum } from '@src/modules/connector/model'
import EventNameEnum from '@model/enum/EventNameEnum'
import MsgModel from '@model/MsgModel'
/* vue */
import VC from '@model/VC'
import Component from 'vue-class-component'
/* util */
import Log from '@src/util/log'
import { message } from '@src/util/message'
import { parse } from '@src/util/lang/object'
import { isFalsy } from '@src/util/type'
import { getTabIdByConnectorJumpUrl } from '@src/modules/connector/util'
/* types */
import { ConnectorInsertSelectCallParams } from '@src/modules/connector/types'
import { t } from '@src/locales'

@Component({ 
  name: ConnectorModuleComponentNameEnum.ConnectorModuleConnectorCreateMixin,
})
export default class ConnectorModuleConnectorCreateMixin extends VC {
  
  /* 是否为连接器新建 */
  private isConnectorFrame: boolean = false
  private isInFrame: boolean = false
  
  /* 连接器新建数据 session 键 */
  public connectorCreateDataSessionKey = ''
  
  /* 连接下新建配置数据 */
  public connectorMessageData: Record<string, any> = {}
  
  /** 
   * @description 连接器新建数据处理
  */
  public connectorInsertSelectCallDataHandler(data: Record<string, any>) {
    Log.warn('not implement connectorInsertSelectCallDataHandler')
  }
  
  get rootElementClassNames() {
    return {
      'in-frame-modal-view': this.isInFrame
    }
  }
  
  /** 
   * @description 获取连接器新建数据
  */
  public fetchConnectorInsertSelectCall() {
    
    // 效验当前窗口是否为连接器新建窗口
    const validateIsConnectorFrameCreate = this.validateIsConnectorFrameCreate()
    if (!validateIsConnectorFrameCreate) {
      console.warn('Caused: [fetchConnectorInsertSelectCall] is not connector frame or is not create or is not connector frame window')
      return
    }
    
    // 连接器新建数据的请求参数
    const params = this.getConnectorInsertSelectCallParams()
    const isNotEmptyParams = Object.values(params).every(Boolean)
    
    if (!isNotEmptyParams) {
      console.warn('getConnectorInsertSelectCall 参数不完整')
      return
    }
    
    getConnectorInsertSelectCall(params).then(result => {
      
      const isFail = MsgModel.isFail(result)
      
      if (isFail) {
        message.error(result?.message || t('common.connector.tips.tip7'))
        return
      }
      
      const data = result?.data || {}
      
      this.connectorInsertSelectCallDataHandler(data)
      
    })
    
  }
  
  /** 
   * @description 获取连接器新建数据的请求参数
  */
  private getConnectorInsertSelectCallParams(): ConnectorInsertSelectCallParams {
    return {
      // 业务类型，TASK-工单，PAAS-paas
      fromBizType: this.connectorMessageData.fromBizType,
      // 业务类型id，比如工单类型id，paas表单类型id
      fromBizTypeId: this.connectorMessageData.fromBizTypeId,
      // 业务主键id
      fromBizId: this.connectorMessageData.fromBizId,
      // 终点业务类型 TASK-工单，PAAS-paas
      toBizType: this.connectorMessageData.toBizType,
      // 终点业务类型id
      toBizTypeId: this.connectorMessageData.toBizTypeId,
    }
  }
  
  /** 
   * @description 从 session 中获取连接器信息
  */
  private getConnectorCreateDataBySessionKey() {
    try {
      
      const connectorCreateDataString = sessionStorage.getItem(this.connectorCreateDataSessionKey)
      
      if (connectorCreateDataString) {
        
        this.isConnectorFrame = true
        
        this.connectorMessageData = parse(connectorCreateDataString)
        
      }
      
    } catch (error) {
      
      Log.error(error, this.getConnectorCreateDataBySessionKey.name)
      
      this.isConnectorFrame = false
      
    }
  }
  
  private onFrameMessageHandler(event: MessageEvent) {
    
    // Log.info(event.data, this.onFrameMessageHandler.name, this.onFrameMessageHandler.name)
    
    const data: { connector: Record<string, any> } = event.data
    
    if (isFalsy(data?.connector)) {
      // Log.info('Caused: [onFrameMessageHandler] data.connector is empty', this.onFrameMessageHandler.name)
      return
    }
    
    this.isInFrame = true
    this.isConnectorFrame = true
    this.connectorMessageData = data.connector
    
    this.onFrameMessageAfterHandler()
    
  }
  
  /**
   * @description 消息处理后的事件
   */
  public onFrameMessageAfterHandler() {
    this.fetchConnectorInsertSelectCall()
  }
  
  /** 
   * @description 发送消息
  */
  private postMessage(data: Record<string, any>) {
    
    Log.info(data, this.postMessage.name, this.postMessage.name)
    
    window.parent.postMessage(data, '*')
    
  }
  
  /** 
   * @description 发送当前页面加载完成消息
  */
  private postReadySuccessMessage() {
    this.postMessage({ ready: true })
  }
  
  /** 
   * @description 发送关闭当前页面消息
  */
  public postCloseDialogMessage() {
    this.postMessage({ close: true })
  }
  
  /** 
   * @description 从 session 中移除连接器信息
  */
  private removeConnectorCreateSessionData() {
    try {
      sessionStorage.removeItem(this.connectorCreateDataSessionKey)
    } catch (error) {
      Log.error(error, this.removeConnectorCreateSessionData.name)
    }
  }
  
  /** 
   * @description 效验当前窗口是否为连接器新建窗口
  */
  private validateIsConnectorFrameCreate() {
    
    try {
      
      const frameId = window?.frameElement?.getAttribute('id') || ''
      const locationUrl = location.href.replace(location.origin, '')
      const tabId = getTabIdByConnectorJumpUrl(locationUrl)
      
      const isConnectorFrameWindow = frameId.includes(tabId)
      
      return this.isConnectorFrame && this.connectorMessageData?.isCreate
      
    } catch (error) {
      
      Log.error(error, this.validateIsConnectorFrameCreate.name)
      
      return false
      
    }
    
  }
  
  /** 
   * @description 校验当前窗口是否在 iframe 中
  */
  public validateCurrentWindowIsInFrame() {
    return this.isInFrame
  }
  
  /** 
   * @description 提交时添加连接器参数
  */
  public setConnectorParamsForSubmit(params: Record<string, any>) {
    // 连接器业务
    try {
      
      // 效验当前窗口是否为连接器新建窗口
      const validateIsConnectorFrameCreate = this.validateIsConnectorFrameCreate()

      if (!validateIsConnectorFrameCreate) {
        console.warn('Caused: [setConnectorParamsForSubmit] is not connector frame or is not create or is not connector frame window')
        return
      }
      
      // 从连接器新建工单
      if (this.connectorMessageData?.isCreate) {
        /**
         * 连接器创建工单时，起始业务
        */
        params.fromBizType = this.connectorMessageData?.fromBizType;
        /**
         * 连接器创建工单时，起始业务类型id
        */
        params.fromBizTypeId = this.connectorMessageData?.fromBizTypeId;
        /**
         * 连接器创建工单时，起始业务id
        */
        params.fromBizId = this.connectorMessageData?.fromBizId;
        /**
         * 连接器创建工单时，起始业务 编号
        */
        params.fromBizNo = this.connectorMessageData?.fromBizNo;
        /**
         * 连接器上报保存关联关系时的参数
        */
        params.connectorParam = {
          processorInstanceId: this.connectorMessageData?.processId
        }
      }
      
    } catch (error) {
      Log.error(error, this.setConnectorParamsForSubmit.name)
    }
  }
  
  created() {
    
    window.addEventListener(EventNameEnum.Message, this.onFrameMessageHandler)
    
    this.postReadySuccessMessage()
    
  }
  
  mounted() {
    this.getConnectorCreateDataBySessionKey()
  }
  
  beforeDestroy() {
    
    window.removeEventListener(EventNameEnum.Message, this.onFrameMessageHandler)
    
    this.removeConnectorCreateSessionData()
    
  }
  
}
